<template>
  <div>
    <h1>this is pinia demo</h1>
    <p class="title">使用state, reset</p>
    <span>counter {{ count }} , doubleValue: {{ doubleValue }}, getters double: {{ double }} name: {{ name }}, age: {{ age }}</span>
    <button @click="increment">increment counter</button>
    <button @click="reset">reset stores</button>
    <div>
      <input v-model="msg"/>
      <p>{{ msg }}</p>
    </div>
    <div>
      <p class="title">patch state</p>
      <button @click="changeStore">count=100,name=alina, age=2,msg=changed!!</button>
    </div>
    <div>
      <p class="title">取消订阅</p>
      <button @click="unsubscribe">unsubscribe</button>
    </div>
    <div>
      <p class="title">订阅相关的回调</p>
      <p>subscribeMsg:{{ tips.subscribeMsg }}</p>
      <p>onActionMsg: {{ tips.onActionMsg }}</p>
    </div>
  </div>
</template>
<script lang="ts">
import { useCounterStore } from '@/stores/counter'
import { storeToRefs } from 'pinia';
import { computed, reactive } from 'vue';
export default {
  name: 'PiniaView',
  setup() {
    const counterStore = useCounterStore()
    const {count, name, age, double,msg} = storeToRefs(counterStore)
    const {increment} = counterStore;

    const tips = reactive({
      subscribeMsg : '未触发',
      onActionMsg: '未触发'
    })

    const reset = () => {
      counterStore.$reset()
    }

    const changeStore = () => {
      counterStore.$patch(state => {
        state.count = 100
        state.name = 'alina'
        state.age = 2
        state.msg = 'changed!!'
      })
    }
    const unsubscribe = counterStore.$subscribe((mutation,state) => {
      tips.subscribeMsg = mutation.type
    })
    
    counterStore.$onAction(({after, onError}) => {
      tips.onActionMsg = 'before onAction'
      after((res)=> {
        tips.onActionMsg = res as string
      })
      onError((err) => {
        tips.onActionMsg = err as string
      })
    })
    return {
      doubleValue: computed(() => counterStore.double),
      count,
      name,
      age,
      msg,
      double,
      increment,
      reset,
      changeStore,
      unsubscribe,
      tips
    }
  }
}
</script>
<style scoped>
.title {
  color: blue;
}
</style>